import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import store from "@/store"

Vue.use(VueRouter)

const routes = [

  {
    path: '/',
    redirect: "/home"
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView
  },
  // {
  //   path: '/free',
  //   name: 'free',
  //   component: () => import(/* webpackChunkName: "free" */ '../views/Free.vue')
  // }
  ,
  {
    path: '/goods',
    name: 'goods',
    component: () => import(/* webpackChunkName: "goods" */ '../views/Goods.vue')
  }
  ,
  // {
  //   path: '/order',
  //   name: 'order',
  //   component: () => import(/* webpackChunkName: "order" */ '../views/Order.vue')
  // }
  ,
  {
    path: '/user',
    name: 'user',
    component: () => import(/* webpackChunkName: "user" */ '../views/User.vue'),
    redirect: "/user/login",
    children: [
      {
        path: 'cart',
        component: () => import(/* webpackChunkName: "cart" */ '../components/user/Cart.vue'),
      },
      {
        path: 'login',
        component: () => import(/* webpackChunkName: "login" */ '../components/user/login.vue'),
      }
    ]
    // 路由独享的守卫
    // beforeEnter: (to, from, next) => {
    //   let token = localStorage.getItem("x-auth-token")
    //   if (token) {
    //     next()
    //   } else {
    //     // alert("请先登录")
    //     store.dispatch("isToastShow/asyncChangisToastShow", {
    //       isshow: true,
    //       msg: "请先登录",
    //       type: "warning"
    //     })
    //     setTimeout(() => {
    //       store.commit("inshowloginmodel/changLogin", true)
    //     }, 1000)
    //   }
    // }
  }

  ,
  {
    path: '/details',
    name: 'details',
    component: () => import(/* webpackChunkName: "details" S*/ '../views/Details.vue')
  },
  {
    path: "*",
    component: () => import(/* webpackChunkName: "*" S*/ '../components/Error.vue')
  }
]

const router = new VueRouter({
  routes,
  mode: "history"
})

// 全局守卫
// router.beforeEach((to, from, next) => {
//   // to: Route: 即将要进入的目标 路由对象
//   // from: Route: 当前导航正要离开的路由
//   // next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
// 当去user页面时, 需要进行是否登录判断, 如果已登录, 正常进入user, 否则不进入提示请先登录
//   if (to.path == "/user") {
//     let token = localStorage.getItem("x-auth-token")
//     if (token) {
//       next()
//     } else {
//       // alert("请先登录")
//       store.dispatch("isToastShow/asyncChangisToastShow", {
//         isshow: true,
//         msg: "请先登录",
//         type: "warning"
//       })
//     }
//   } else {
//     next()
//   }

// })


// 处理连续点击路由错误





const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch(err => { })
};


export default router
